<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>处理JSON数据</title>
    <style>
    	#box{
    		width: 800px;
    		border: 1px solid #000;
    		padding: 20px;
    		background-color:#feeeed;
    	}
    </style>
</head>
<body>
    <h1>处理JSON数据</h1>
    <hr>
    <button onclick="loadHtml()">加载</button>
    <hr>

    <hr>
    <div id="box"></div>

    <script>
    // var a = '{"name":"芸芸","age":"18"}';
    // console.log(a);

    // var a = 'var yy = {"name":"芸芸","age":"18"}';
    // eval(a);
    // console.log(yy);

    // var yy = eval('{"name":"芸芸","age":"18"}');
    // var yy = eval('({"name":"芸芸","age":"1888"})');
    // console.log(yy);

    // JSON 解析器
    // var yy = JSON.parse('{"name":"芸芸2号","age":"18"}');
    // console.log(yy);
    
    function loadHtml(){
    	var xhr = new XMLHttpRequest();
    	xhr.onreadystatechange = function(){
    		if(xhr.readyState == 4){
    			if(xhr.status == 200){
    				// console.log(xhr.responseText);
    				// 清空之前的数据
    				box.innerHTML = '';
    				var jsonStr = xhr.responseText;
    				//eval('var obj = '+ jsonStr);
    				//var obj = eval('(+jsonStr+)');
    				var obj = JSON.parse(jsonStr);
    				console.log(obj);

    				//生成表格
    				var table = document.createElement('table');
    				table.width = 800;
    				table.border = 1;
    				table.cellSpacing = 0;
    				table.cellPadding = 5;
    				table.id ='table';
    				console.log(table);
    				box.appendChild(table);

    				//添加表头
    				var tr = table.insertRow(0);
    				addTH(tr,['ID','NAME','SEX','AGE','PRO']);

    				//向表格添加数据
    				for (var i = 0; i < obj.length; i++) {
    					var tr = table.insertRow(i+1);
    					tr.insertCell(0).innerHTML = obj[i].id;
    					tr.insertCell(1).innerHTML = obj[i].name;
    					tr.insertCell(2).innerHTML = obj[i].sex;
    					tr.insertCell(3).innerHTML = obj[i].age;
    					tr.insertCell(4).innerHTML = obj[i].province;
    				}

    			}
    		}
    	}
    	xhr.open('get','./php/4.php',true);
    	xhr.send();
    }
    
	function addTH(tr,data){
		for (var i = 0; i < data.length; i++) {
			var th=document.createElement('th');
			th.innerHTML = data[i];
			tr.appendChild(th);
		}
	}
    </script>

</body>
</html>